package org.timemachine.generator;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.timemachine.generator.spi.Persistency;
import org.timemachine.util.FileUtil;

public class PersistencyImpl implements Persistency {
	
	private final static String persistencePath =  "\\src\\META-INF\\persistence.xml";
	private final static String timeMachineJar = "timeMachineChangeClasses.jar";

	@Override
	public File findPersistence(String projectPath) throws Exception {
		File prsFile = FileUtil.getExistingFileByProjectPath(projectPath + persistencePath);

		/*DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc =  dBuilder.parse(fi);

		doc.getDocumentElement().normalize();
		
		NodeList nList = doc.getElementsByTagName("persistence-unit");
		
		for (int i = 0; i < nList.getLength(); i++) {
			Node node = nList.item(i);
			if (node.getNodeType() == Node.ENTITY_NODE) {
				NodeList list = node.getChildNodes();
				for (int j = 0; j < nList.getLength(); j++) {
					Node n = list.item(j);
					if (n.getNodeType() == Node.ELEMENT_NODE) {
						Element el = (Element) n;
						el.getAttribute("jar-file");
					}
				}
			}
		}
		*/
		
		return prsFile;		
	}

	@Override
	public void injectChangeJar(File persFile) throws Exception {		
		BufferedReader rdr = new BufferedReader(new FileReader(persFile));
			
		String line;
		String newFileString = "";
		boolean isJar = false;
	
		while ((line = rdr.readLine()) != null) {
			if (line.contains("</jta-data-source>")) {
				int beginIndex = line.indexOf("</jta-data-source>");
				int endIndex = beginIndex + (new String("</jta-data-source>")).length();
				newFileString = newFileString.concat(line.substring(0, endIndex)).concat("\n");
				newFileString = newFileString.concat("\t\t").concat("<jar-file>").concat(timeMachineJar).concat("</jar-file>").concat("\n");
				if (endIndex!=line.length()) {
					newFileString = newFileString.concat(line.substring(endIndex,line.length())).concat("\n");
				}
			} else {
				newFileString = newFileString.concat(line).concat("\n");				
			}
			if (line.contains(timeMachineJar)) {
				isJar = true;
				System.out.println(timeMachineJar + " persistence.xml'de var");
				break;
			}
		}
		rdr.close();
	
		if (!isJar) {
			BufferedWriter wrt = new BufferedWriter(new FileWriter(persFile));

			wrt.write(newFileString);	
			wrt.flush();
			wrt.close();
			System.out.println(timeMachineJar + " persistence.xml'de yok, eklendi");
		}
		
	}

	@Override
	public void injectChangeClasses(File persFile, Set<String> clazzes) throws Exception {		

		Map<String, String> clazzMap = new HashMap<String, String>();
		for (String clazzName: clazzes) {
			clazzMap.put(clazzName, clazzName);
		}

		BufferedReader rdr = new BufferedReader(new FileReader(persFile));
			
		String line;
		String newFileString = "";
		boolean canClassBeAddded = false;
		boolean isAnyClassAdded = false;
	
		while ((line = rdr.readLine()) != null) {
			String removalClazz = null;
			if (canClassBeAddded) {
				for (String clazzName : clazzes) {
					if (line.contains(clazzName) && line.contains("</class>")) {
						removalClazz = clazzName;
						break;
					} 
				}
				if (removalClazz!=null) {
					clazzes.remove(removalClazz);
				} else {
					for (String remindClazzName: clazzes) {
						newFileString = newFileString.concat("\t\t").concat("<class>").concat(remindClazzName).concat("</class>").concat("\n");						
						System.out.println(remindClazzName + " persistence.xml'e eklendi");
					}
					isAnyClassAdded = true;
					canClassBeAddded = false;
				}
			}

			if (line.contains("<jar-file>"+ timeMachineJar + "</jar-file>")) {
				canClassBeAddded = true;
			}

			newFileString = newFileString.concat(line).concat("\n");				
		}

		rdr.close();
	
		if (isAnyClassAdded) {
			BufferedWriter wrt = new BufferedWriter(new FileWriter(persFile));
	
			wrt.write(newFileString);	
			wrt.flush();
			wrt.close();
		} else {
			System.out.println("Herhangi bir change class perrsistence.xml'e eklenmedi");			
		}
		
	}

}
